<template>
  <div class="login_form">
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm Sign_in"
    >
      <h1 style="text-align: center;">依谷管理系统</h1>
      <el-form-item label="账号" prop="name">
        <el-input v-model="ruleForm.name" class="ipt_dl"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="ruleForm.password" class="ipt_dl" show-password></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import logIn from '@/api/login'
export default {
  data() {
    return {
      ruleForm: {
        name: "",
        type: [],
        inputss: '',
        password: ""
      },
      rules: {
        name: [
          { required: true, message: "请输入账号", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, max: 16, message: "长度在 8 到 16 个字符", trigger: ['blur', 'change'] }
        ]
      }
    };
  },
  created() {},
  watch: {},
  methods: {
      //认证正则账号、密码
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {//认证成功
        //   alert("成功");
        this.checkLogin()
            // logIn.loginIn(this.ruleForm.name, this.ruleForm.password)
            
        } else {
          console.log("失败");
          return false;
        }
      });
    },
    async checkLogin() {
        try{
            let p = await logIn.loginIn(this.ruleForm.name, this.ruleForm.password)
            // console.log(p.data)
            if(p.data.flag){
                //验证通过，把 token 发送给后端，获取用户信息
                // console.log(p.data.data.token)
                this.checkToken(p.data.data.token)
            }else{
                this.$message.error("用户名或密码错误")
            }
        }catch(err){
            console.log(err)
        }
    },
    async checkToken(token) {
        try{
            let p = await logIn.getuserIn(token)
            if(p.data.flag){
                //验证通过
                this.$message("登陆成功")
                //并且把token和用户名存储到本地存储localstorage
                localStorage.setItem("jinfeng-mms-username", p.data.data.name);
                localStorage.setItem("jinfeng-mms-token", token);
                //跳转到首页
                this.$router.push("/");
            }else{
                this.$message.error("登录失败")
            }
        }catch(err){
            console.log(err)
        }
    }
  },
  components: {}
};
</script>

<style scoped lang="scss">
@import url('~@/assets/css/login.css');

</style>
